package com.kly.springbootinit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kly.springbootinit.common.ErrorCode;
import com.kly.springbootinit.exception.ThrowUtils;
import com.kly.springbootinit.mapper.ReservationMapper;
import com.kly.springbootinit.model.dto.reservation.ReservationAddRequest;
import com.kly.springbootinit.model.entity.Reservation;
import com.kly.springbootinit.model.entity.Vehicle;
import com.kly.springbootinit.model.enums.VehicleStatus;
import com.kly.springbootinit.model.vo.ReservationVO;
import com.kly.springbootinit.service.ReservationService;
import com.kly.springbootinit.service.VehicleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author admin
 * @description 针对表【reservation(预约表)】的数据库操作Service实现
 * @createDate 2025-05-21 14:34:14
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation>
        implements ReservationService {

    @Resource
    private VehicleService vehicleService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReservationVO createReservation(ReservationAddRequest reservationAddRequest) {
        ThrowUtils.throwIf(reservationAddRequest == null, ErrorCode.PARAMS_ERROR, "预约参数不能为空");
        Vehicle vehicleDb = vehicleService.getById(reservationAddRequest.getVehicleId());
        Integer status = vehicleDb.getStatus();
        // 判断车辆状态 是否可预约
        ThrowUtils.throwIf(Objects.equals(VehicleStatus.MAINTENANCE.getStatus(), status) || Objects.equals(VehicleStatus.RESERVED.getStatus(), status), ErrorCode.OPERATION_ERROR, "车辆状态不可预约");
        Reservation reservation = new Reservation();
        reservation.setVehicleId(reservationAddRequest.getVehicleId());
        reservation.setUserId(reservationAddRequest.getUserId());
        reservation.setStartTime(reservationAddRequest.getStartTime());
        reservation.setEndTime(reservationAddRequest.getEndTime());
        reservation.setStatus(1);
        // 保存
        boolean save = this.save(reservation);

        // 修改车辆状态
        boolean update = vehicleService.lambdaUpdate()
                .eq(Vehicle::getId, reservation.getVehicleId())
                .set(Vehicle::getStatus, VehicleStatus.RESERVED.getStatus())
                .update();

        ThrowUtils.throwIf(!save || !update, ErrorCode.OPERATION_ERROR, "预约失败");

        return BeanUtil.copyProperties(reservation, ReservationVO.class);
    }
}




